package com.springcloud.eshop.aggrdata.rabbitmq.strategy;

import com.alibaba.fastjson.JSON;
import com.springcloud.eshop.aggrdata.rabbitmq.factory.AggrDataChangeHandlerFactory;
import com.springcloud.eshop.entity.*;
import com.springcloud.eshop.enums.DataTypeEnum;
import com.springcloud.eshop.message.AggrDataChangeMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * @Desc:
 * @Date: 2020-07-02
 * @Version:v1.0
 */
@Service
public class ProductAggrDataChangeStrategy extends BaseAggrDataChangeHandler implements InitializingBean {

    @Autowired
    private JedisPool jedisPool;

    @Override
    public boolean handler(AggrDataChangeMessage aggrDataChangeMessage) {
        long id = aggrDataChangeMessage.getId();
        String productJsonStr = jedisPool.getResource().get(getRedisKey(id));
        if (StringUtils.isNotEmpty(productJsonStr)) {
            AggrProduct aggrProduct = new AggrProduct();
            aggrProduct.setProduct(JSON.parseObject(productJsonStr, Product.class));

            String[] redKeys = new String[]{"product_intro_detail_" + id, "product_specification_detail_" + id, "product_property_detail_" + id};

            List<String> jsonStrs = jedisPool.getResource().mget(redKeys);

            // 商品介绍信息
            // String productIntroJsonStr = jedisPool.getResource().get("product_intro_detail_" + id);
            if (StringUtils.isNotEmpty(jsonStrs.get(0))) {
                aggrProduct.setProductIntro(JSON.parseObject(jsonStrs.get(0), ProductIntro.class));
            }

            // 商品规格
            // String productSpecificationJsonStr = jedisPool.getResource().get("product_specification_detail_" + id);
            if (StringUtils.isNotEmpty(jsonStrs.get(1))) {
                aggrProduct.setProductSpecification(JSON.parseObject(jsonStrs.get(1), ProductSpecification.class));
            }

            // 商品属性
            // String productPropertyJsonStr = jedisPool.getResource().get("product_property_detail_" + id);
            if (StringUtils.isNotEmpty(jsonStrs.get(2))) {
                aggrProduct.setProductProperty(JSON.parseObject(jsonStrs.get(2), ProductProperty.class));
            }
            jedisPool.getResource().set("dim_product_" + id, JSON.toJSONString(aggrProduct));
        } else {
            jedisPool.getResource().del("dim_product_" + id);
        }
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        AggrDataChangeHandlerFactory.register(DataTypeEnum.PRODUCT.getType(), this);
    }

    @Override
    public String getRedisKey(long id) {
        return "product_detail_" + id;
    }
}
